package com.example.easycharge.schedule;

import com.example.easycharge.entity.Bill;
import com.example.easycharge.notRepEntity.WaitQueue;
import com.example.easycharge.repository.ChargePileRepository;
import com.example.easycharge.service.BillService;
import com.example.easycharge.service.ChargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

@Component
public class ChargeTiming {

    @Autowired
    private ChargeService chargeService;
    @Autowired
    private BillService billService;
    @Autowired
    private ChargePileRepository chargePileRepository;


    //    @Scheduled(fixedDelay = 60000, initialDelay = 10000)
    // 每分钟改成每6秒
    @Scheduled(fixedDelay = 6000, initialDelay = 1000)
    public void chargeTiming() {
        HashMap<Long, WaitQueue> waitQueueMap = chargeService.getWaitQueue();
        // 定时任务，每分钟将每个队列中充电的那个车时间减1
        Date nowDate = new Date();
        int nowHour = nowDate.getHours();
        int peak = billService.peakCheck(nowHour);
        chargePileRepository.addWorkMinutes();
        double overtimeMoneyPreHour = billService.getOvertimeMoneyPreHour();
        for (WaitQueue waitQueue : waitQueueMap.values()) {
            if (waitQueue.getChargingVehicle() == null) {
                continue;
            }
            long vehicleId = waitQueue.getChargingVehicle().getVehicleId();
            if (waitQueue.isCharge()) {
                // 如果正在充电的话
                waitQueue.minutesTick();
                billService.addChargeBill(vehicleId, peak);
                chargePileRepository.addChargeMinutes(waitQueue.getPileID());
                // 如果充满了（剩余充电时间为0）
                if (waitQueue.getLeftMinutes() == 0) {
                    waitQueue.finishCharge();
                    billService.endCharge(vehicleId);
                }
            } else {
                waitQueue.waitTick();
                Bill thisBill = billService.getBill(vehicleId);
                thisBill.overtimeMinutesTick();
                if (thisBill.getOvertimeMinutes() % 60 == 0) {
                    thisBill.overtimeMoneyAdd(overtimeMoneyPreHour);
                }
            }
        }
    }

    @Scheduled(fixedDelay = 360000, initialDelay = 1000)
    public void hourAdd() {
        billService.hourAdd();
    }
}
